import { useState, useEffect } from 'react'
import {
  Card,
  Tabs,
  Typography,
  Form,
  Input,
  InputNumber,
  Button,
  Message,
  Table,
  Space,
  Modal,
  Popconfirm,
  Tag,
  Switch,
  Select,
  Alert,
} from '@arco-design/web-react'
import {
  IconSave,
  IconPlus,
  IconEdit,
  IconDelete,
  IconLock,
  IconUnlock,
  IconRefresh,
  IconInfoCircle,
  IconPoweroff,
  IconCheckCircle,
} from '@arco-design/web-react/icon'
import {
  getNetworkConfig,
  updateNetworkConfig,
  getGitConfig,
  updateGitConfig,
  getSystemGeneralConfig,
  updateSystemGeneralConfig,
} from '@/api/systemConfig'
import {
  getPendingRestart,
  gracefulShutdown,
  getSystemStatus,
  type SystemStatus,
  type PendingRestartResponse,
} from '@/api/systemService'
import {
  getUsers,
  createUser,
  updateUser,
  deleteUser,
  lockUser,
  unlockUser,
  resetUserPassword,
  getRoles,
  createRole,
  updateRole,
  deleteRole,
  getPermissions,
  getUserRoles,
  assignRolesToUser,
} from '@/api/user'
import type {
  User,
  Role,
  Permission,
  CreateUserRequest,
  CreateRoleRequest,
} from '@/api/user'
import './index.css'

const { Title } = Typography
const { TabPane } = Tabs
const FormItem = Form.Item

export default function Settings() {
  const [loading, setLoading] = useState(false)
  const [activeTab, setActiveTab] = useState('network')

  // ============= 网络配置 =============
  const [networkForm] = Form.useForm()
  const [networkLoading, setNetworkLoading] = useState(false)

  useEffect(() => {
    if (activeTab === 'network') {
      loadNetworkConfig()
    }
  }, [activeTab])

  const loadNetworkConfig = async () => {
    try {
      const config = await getNetworkConfig()
      networkForm.setFieldsValue(config)
    } catch (error) {
      console.error('Failed to load network config:', error)
      // 如果API不存在,设置默认值
      networkForm.setFieldsValue({
        controlApiPort: 5136,
        tcpServerPort: 5137,
        nodeDefaultPort: 5138,
        websocketPort: 5136,
      })
    }
  }

  const handleSaveNetwork = async (values: any) => {
    setNetworkLoading(true)
    try {
      await updateNetworkConfig(values)
      Message.success('网络配置已保存')
    } catch (error) {
      console.error('Failed to save network config:', error)
      Message.error('保存失败')
    } finally {
      setNetworkLoading(false)
    }
  }

  // ============= Git 配置 =============
  const [gitForm] = Form.useForm()
  const [gitLoading, setGitLoading] = useState(false)

  useEffect(() => {
    if (activeTab === 'git') {
      loadGitConfig()
    }
  }, [activeTab])

  const loadGitConfig = async () => {
    try {
      const config = await getGitConfig()
      gitForm.setFieldsValue(config)
    } catch (error) {
      console.error('Failed to load git config:', error)
      // 如果API不存在,设置默认值
      gitForm.setFieldsValue({
        defaultBranch: 'main',
        cloneTimeout: 300,
        enableShallowClone: true,
        defaultCloneDepth: 1,
      })
    }
  }

  const handleSaveGit = async (values: any) => {
    setGitLoading(true)
    try {
      await updateGitConfig(values)
      Message.success('Git 配置已保存')
    } catch (error) {
      console.error('Failed to save git config:', error)
      Message.error('保存失败')
    } finally {
      setGitLoading(false)
    }
  }

  // ============= 系统配置 =============
  const [systemForm] = Form.useForm()
  const [systemLoading, setSystemLoading] = useState(false)

  useEffect(() => {
    if (activeTab === 'system') {
      loadSystemConfig()
    }
  }, [activeTab])

  const loadSystemConfig = async () => {
    try {
      const config = await getSystemGeneralConfig()
      systemForm.setFieldsValue(config)
    } catch (error) {
      console.error('Failed to load system config:', error)
      // 如果API不存在,设置默认值
      systemForm.setFieldsValue({
        maxConcurrentTasks: 10,
        taskTimeoutMinutes: 60,
        logRetentionDays: 30,
        enableMetrics: true,
      })
    }
  }

  const handleSaveSystem = async (values: any) => {
    setSystemLoading(true)
    try {
      await updateSystemGeneralConfig(values)
      Message.success('系统配置已保存')
    } catch (error) {
      console.error('Failed to save system config:', error)
      Message.error('保存失败')
    } finally {
      setSystemLoading(false)
    }
  }

  // ============= 用户管理 =============
  const [users, setUsers] = useState<User[]>([])
  const [userModalVisible, setUserModalVisible] = useState(false)
  const [editingUser, setEditingUser] = useState<User | null>(null)
  const [userForm] = Form.useForm()
  const [resetPasswordModalVisible, setResetPasswordModalVisible] =
    useState(false)
  const [resetPasswordForm] = Form.useForm()
  const [selectedUserId, setSelectedUserId] = useState<number | null>(null)
  const [roleModalVisible, setRoleModalVisible] = useState(false)
  const [selectedUserRoles, setSelectedUserRoles] = useState<number[]>([])
  const [allRoles, setAllRoles] = useState<Role[]>([])

  useEffect(() => {
    if (activeTab === 'users') {
      loadUsers()
      loadRoles()
    }
  }, [activeTab])

  const loadUsers = async () => {
    setLoading(true)
    try {
      const data = await getUsers()
      setUsers(data)
    } catch (error) {
      console.error('Failed to load users:', error)
      // 不显示错误消息,避免干扰用户
      setUsers([])
    } finally {
      setLoading(false)
    }
  }

  const loadRoles = async () => {
    try {
      const data = await getRoles()
      setAllRoles(data)
    } catch (error) {
      console.error('Failed to load roles:', error)
      setAllRoles([])
    }
  }

  const handleCreateUser = () => {
    setEditingUser(null)
    userForm.resetFields()
    setUserModalVisible(true)
  }

  const handleEditUser = (user: User) => {
    setEditingUser(user)
    userForm.setFieldsValue({
      username: user.username,
      email: user.email,
      displayName: user.displayName,
    })
    setUserModalVisible(true)
  }

  const handleSaveUser = async () => {
    try {
      const values = await userForm.validate()

      if (editingUser) {
        // 更新用户
        await updateUser(editingUser.userId, {
          email: values.email,
          displayName: values.displayName,
        })
        Message.success('用户已更新')
      } else {
        // 创建用户
        const createData: CreateUserRequest = {
          username: values.username,
          password: values.password,
          email: values.email,
          displayName: values.displayName,
        }
        await createUser(createData)
        Message.success('用户已创建')
      }

      setUserModalVisible(false)
      loadUsers()
    } catch (error) {
      console.error('Failed to save user:', error)
      Message.error('保存失败')
    }
  }

  const handleDeleteUser = async (userId: number) => {
    try {
      await deleteUser(userId)
      Message.success('用户已删除')
      loadUsers()
    } catch (error) {
      console.error('Failed to delete user:', error)
      Message.error('删除失败')
    }
  }

  const handleLockUser = async (userId: number) => {
    try {
      await lockUser(userId)
      Message.success('用户已锁定')
      loadUsers()
    } catch (error) {
      console.error('Failed to lock user:', error)
      Message.error('锁定失败')
    }
  }

  const handleUnlockUser = async (userId: number) => {
    try {
      await unlockUser(userId)
      Message.success('用户已解锁')
      loadUsers()
    } catch (error) {
      console.error('Failed to unlock user:', error)
      Message.error('解锁失败')
    }
  }

  const handleResetPassword = (userId: number) => {
    setSelectedUserId(userId)
    resetPasswordForm.resetFields()
    setResetPasswordModalVisible(true)
  }

  const handleSaveResetPassword = async () => {
    try {
      const values = await resetPasswordForm.validate()
      if (selectedUserId) {
        await resetUserPassword(selectedUserId, {
          newPassword: values.newPassword,
        })
        Message.success('密码已重置')
        setResetPasswordModalVisible(false)
      }
    } catch (error) {
      console.error('Failed to reset password:', error)
      Message.error('重置密码失败')
    }
  }

  const handleManageUserRoles = async (user: User) => {
    setSelectedUserId(user.userId)
    try {
      const userRoles = await getUserRoles(user.userId)
      setSelectedUserRoles(userRoles.map((r) => r.roleId))
      setRoleModalVisible(true)
    } catch (error) {
      console.error('Failed to load user roles:', error)
      Message.error('加载用户角色失败')
    }
  }

  const handleSaveUserRoles = async () => {
    if (selectedUserId) {
      try {
        await assignRolesToUser(selectedUserId, selectedUserRoles)
        Message.success('角色已分配')
        setRoleModalVisible(false)
        loadUsers()
      } catch (error) {
        console.error('Failed to assign roles:', error)
        Message.error('分配角色失败')
      }
    }
  }

  // ============= 角色管理 =============
  const [roles, setRoles] = useState<Role[]>([])
  const [roleFormModalVisible, setRoleFormModalVisible] = useState(false)
  const [editingRole, setEditingRole] = useState<Role | null>(null)
  const [roleForm] = Form.useForm()
  const [permissions, setPermissions] = useState<Permission[]>([])

  useEffect(() => {
    if (activeTab === 'roles') {
      loadRolesData()
      loadPermissions()
    }
  }, [activeTab])

  const loadRolesData = async () => {
    setLoading(true)
    try {
      const data = await getRoles()
      setRoles(data)
    } catch (error) {
      console.error('Failed to load roles:', error)
      setRoles([])
    } finally {
      setLoading(false)
    }
  }

  const loadPermissions = async () => {
    try {
      const data = await getPermissions()
      setPermissions(data)
    } catch (error) {
      console.error('Failed to load permissions:', error)
      setPermissions([])
    }
  }

  const handleCreateRole = () => {
    setEditingRole(null)
    roleForm.resetFields()
    setRoleFormModalVisible(true)
  }

  const handleEditRole = (role: Role) => {
    setEditingRole(role)
    roleForm.setFieldsValue({
      roleName: role.roleName,
      description: role.description,
      permissionIds: role.permissions?.map((p) => p.permissionId) || [],
    })
    setRoleFormModalVisible(true)
  }

  const handleSaveRole = async () => {
    try {
      const values = await roleForm.validate()

      if (editingRole) {
        await updateRole(editingRole.roleId, {
          description: values.description,
          permissionIds: values.permissionIds,
        })
        Message.success('角色已更新')
      } else {
        const createData: CreateRoleRequest = {
          roleName: values.roleName,
          description: values.description,
          permissionIds: values.permissionIds || [],
        }
        await createRole(createData)
        Message.success('角色已创建')
      }

      setRoleFormModalVisible(false)
      loadRolesData()
    } catch (error) {
      console.error('Failed to save role:', error)
      Message.error('保存失败')
    }
  }

  const handleDeleteRole = async (roleId: number) => {
    try {
      await deleteRole(roleId)
      Message.success('角色已删除')
      loadRolesData()
    } catch (error) {
      console.error('Failed to delete role:', error)
      Message.error('删除失败')
    }
  }

  // ============= 系统服务管理 =============
  const [systemStatus, setSystemStatus] = useState<SystemStatus | null>(null)
  const [pendingRestart, setPendingRestart] = useState<PendingRestartResponse | null>(null)
  const [serviceLoading, setServiceLoading] = useState(false)

  useEffect(() => {
    if (activeTab === 'service') {
      loadSystemStatus()
      loadPendingRestart()
    }
  }, [activeTab])

  const loadSystemStatus = async () => {
    setServiceLoading(true)
    try {
      const data = await getSystemStatus()
      setSystemStatus(data)
    } catch (error) {
      console.error('Failed to load system status:', error)
      Message.error('加载系统状态失败')
    } finally {
      setServiceLoading(false)
    }
  }

  const loadPendingRestart = async () => {
    try {
      const data = await getPendingRestart()
      setPendingRestart(data)
    } catch (error) {
      console.error('Failed to load pending restart:', error)
    }
  }

  const handleGracefulShutdown = async () => {
    Modal.confirm({
      title: '确认关闭系统',
      content: '此操作将优雅关闭系统服务。所有正在运行的任务将被中止,确定要继续吗?',
      okButtonProps: { status: 'danger' },
      onOk: async () => {
        try {
          await gracefulShutdown()
          Message.success('系统关闭指令已发送')
          setTimeout(() => {
            loadSystemStatus()
          }, 2000)
        } catch (error) {
          console.error('Failed to shutdown system:', error)
          Message.error('系统关闭失败')
        }
      },
    })
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'Running':
        return 'green'
      case 'Stopping':
        return 'orange'
      case 'Stopped':
        return 'red'
      default:
        return 'gray'
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'Running':
        return '运行中'
      case 'Stopping':
        return '停止中'
      case 'Stopped':
        return '已停止'
      default:
        return '未知'
    }
  }

  return (
    <div className="settings-page">
      <Title heading={4} style={{ marginBottom: 20 }}>
        系统设置
      </Title>

      <Card>
        <Tabs activeTab={activeTab} onChange={setActiveTab} type="card-gutter">
          {/* 网络配置 */}
          <TabPane key="network" title="网络配置">
            <Alert
              type="info"
              content="配置系统各服务的网络端口。修改后需要重启服务才能生效。"
              closable
              style={{ marginBottom: 24 }}
            />
            <Form
              form={networkForm}
              layout="vertical"
              onSubmit={handleSaveNetwork}
              style={{ maxWidth: 600 }}>
              <FormItem
                label="控制面板端口"
                field="controlApiPort"
                rules={[{ required: true, message: '请输入控制面板端口' }]}>
                <InputNumber
                  placeholder="请输入端口号"
                  min={1}
                  max={65535}
                  style={{ width: '100%' }}
                />
              </FormItem>

              <FormItem
                label="TCP 服务端口"
                field="tcpServerPort"
                rules={[{ required: true, message: '请输入 TCP 服务端口' }]}>
                <InputNumber
                  placeholder="请输入端口号"
                  min={1}
                  max={65535}
                  style={{ width: '100%' }}
                />
              </FormItem>

              <FormItem
                label="节点默认端口"
                field="nodeDefaultPort"
                rules={[{ required: true, message: '请输入节点默认端口' }]}>
                <InputNumber
                  placeholder="请输入端口号"
                  min={1}
                  max={65535}
                  style={{ width: '100%' }}
                />
              </FormItem>

              <FormItem
                label="WebSocket 端口"
                field="websocketPort"
                rules={[{ required: true, message: '请输入 WebSocket 端口' }]}>
                <InputNumber
                  placeholder="请输入端口号"
                  min={1}
                  max={65535}
                  style={{ width: '100%' }}
                />
              </FormItem>

              <FormItem>
                <Button
                  type="primary"
                  htmlType="submit"
                  icon={<IconSave />}
                  loading={networkLoading}>
                  保存配置
                </Button>
              </FormItem>
            </Form>
          </TabPane>

          {/* Git 配置 */}
          <TabPane key="git" title="Git 配置">
            <Alert
              type="info"
              content="配置 Git 仓库克隆和拉取的默认行为。"
              closable
              style={{ marginBottom: 24 }}
            />
            <Form
              form={gitForm}
              layout="vertical"
              onSubmit={handleSaveGit}
              style={{ maxWidth: 600 }}>
              <FormItem
                label="默认分支"
                field="defaultBranch"
                rules={[{ required: true, message: '请输入默认分支' }]}>
                <Input placeholder="main" />
              </FormItem>

              <FormItem
                label="克隆超时(秒)"
                field="cloneTimeout"
                rules={[{ required: true, message: '请输入克隆超时时间' }]}>
                <InputNumber
                  placeholder="300"
                  min={1}
                  style={{ width: '100%' }}
                />
              </FormItem>

              <FormItem label="启用浅克隆" field="enableShallowClone">
                <Switch />
              </FormItem>

              <FormItem
                label="默认克隆深度"
                field="defaultCloneDepth"
                rules={[{ required: true, message: '请输入默认克隆深度' }]}>
                <InputNumber
                  placeholder="1"
                  min={1}
                  style={{ width: '100%' }}
                />
              </FormItem>

              <FormItem>
                <Button
                  type="primary"
                  htmlType="submit"
                  icon={<IconSave />}
                  loading={gitLoading}>
                  保存配置
                </Button>
              </FormItem>
            </Form>
          </TabPane>

          {/* 系统配置 */}
          <TabPane key="system" title="系统配置">
            <Alert
              type="info"
              content="配置系统运行的全局参数,影响任务执行和资源管理。"
              closable
              style={{ marginBottom: 24 }}
            />
            <Form
              form={systemForm}
              layout="vertical"
              onSubmit={handleSaveSystem}
              style={{ maxWidth: 600 }}>
              <FormItem
                label="最大并发任务数"
                field="maxConcurrentTasks"
                rules={[{ required: true, message: '请输入最大并发任务数' }]}>
                <InputNumber
                  placeholder="10"
                  min={1}
                  style={{ width: '100%' }}
                />
              </FormItem>

              <FormItem
                label="任务超时时间(分钟)"
                field="taskTimeoutMinutes"
                rules={[{ required: true, message: '请输入任务超时时间' }]}>
                <InputNumber
                  placeholder="60"
                  min={1}
                  style={{ width: '100%' }}
                />
              </FormItem>

              <FormItem
                label="日志保留天数"
                field="logRetentionDays"
                rules={[{ required: true, message: '请输入日志保留天数' }]}>
                <InputNumber
                  placeholder="30"
                  min={1}
                  style={{ width: '100%' }}
                />
              </FormItem>

              <FormItem label="启用指标收集" field="enableMetrics">
                <Switch />
              </FormItem>

              <FormItem>
                <Button
                  type="primary"
                  htmlType="submit"
                  icon={<IconSave />}
                  loading={systemLoading}>
                  保存配置
                </Button>
              </FormItem>
            </Form>
          </TabPane>

          {/* 用户管理 */}
          <TabPane key="users" title="用户管理">
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              <Alert
                type="info"
                content="管理系统用户账户、权限和角色分配。"
                closable
              />
              <div>
                <Button
                  type="primary"
                  icon={<IconPlus />}
                  onClick={handleCreateUser}>
                  创建用户
                </Button>
              </div>

              <Table
                loading={loading}
                data={users}
                pagination={{ pageSize: 10 }}
                rowKey="userId"
                columns={[
                  { title: '用户名', dataIndex: 'username' },
                  { title: '显示名', dataIndex: 'displayName' },
                  { title: '邮箱', dataIndex: 'email' },
                  {
                    title: '状态',
                    dataIndex: 'isLocked',
                    render: (isLocked: boolean) =>
                      isLocked ? (
                        <Tag color="red">已锁定</Tag>
                      ) : (
                        <Tag color="green">正常</Tag>
                      ),
                  },
                  {
                    title: '操作',
                    render: (_: any, record: User) => (
                      <Space>
                        <Button
                          size="small"
                          onClick={() => handleEditUser(record)}>
                          编辑
                        </Button>
                        <Button
                          size="small"
                          onClick={() => handleManageUserRoles(record)}>
                          角色
                        </Button>
                        <Button
                          size="small"
                          icon={<IconRefresh />}
                          onClick={() => handleResetPassword(record.userId)}>
                          重置密码
                        </Button>
                        {record.isLocked ? (
                          <Button
                            size="small"
                            icon={<IconUnlock />}
                            onClick={() => handleUnlockUser(record.userId)}>
                            解锁
                          </Button>
                        ) : (
                          <Button
                            size="small"
                            icon={<IconLock />}
                            onClick={() => handleLockUser(record.userId)}>
                            锁定
                          </Button>
                        )}
                        <Popconfirm
                          title="确定要删除此用户吗?"
                          onOk={() => handleDeleteUser(record.userId)}>
                          <Button
                            size="small"
                            status="danger"
                            icon={<IconDelete />}>
                            删除
                          </Button>
                        </Popconfirm>
                      </Space>
                    ),
                  },
                ]}
              />
            </Space>
          </TabPane>

          {/* 角色管理 */}
          <TabPane key="roles" title="角色管理">
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              <Alert
                type="info"
                content="管理系统角色和权限分配。角色可以包含多个权限,用户可以拥有多个角色。"
                closable
              />
              <div>
                <Button
                  type="primary"
                  icon={<IconPlus />}
                  onClick={handleCreateRole}>
                  创建角色
                </Button>
              </div>

              <Table
                loading={loading}
                data={roles}
                pagination={{ pageSize: 10 }}
                rowKey="roleId"
                columns={[
                  { title: '角色名称', dataIndex: 'roleName' },
                  { title: '描述', dataIndex: 'description' },
                  {
                    title: '权限数',
                    dataIndex: 'permissions',
                    render: (permissions: Permission[]) =>
                      permissions?.length || 0,
                  },
                  {
                    title: '操作',
                    render: (_: any, record: Role) => (
                      <Space>
                        <Button
                          size="small"
                          icon={<IconEdit />}
                          onClick={() => handleEditRole(record)}>
                          编辑
                        </Button>
                        <Popconfirm
                          title="确定要删除此角色吗?"
                          onOk={() => handleDeleteRole(record.roleId)}>
                          <Button
                            size="small"
                            status="danger"
                            icon={<IconDelete />}>
                            删除
                          </Button>
                        </Popconfirm>
                      </Space>
                    ),
                  },
                ]}
              />
            </Space>
          </TabPane>

          {/* 系统服务管理 */}
          <TabPane key="service" title="系统服务">
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              <Alert
                type="info"
                content="查看系统运行状态,管理系统服务的启动和关闭。"
                closable
              />

              {/* 系统状态信息 */}
              <Card title="系统状态" loading={serviceLoading}>
                {systemStatus && (
                  <Space direction="vertical" size="medium" style={{ width: '100%' }}>
                    <Space size="large">
                      <div>
                        <Text type="secondary">状态: </Text>
                        <Tag color={getStatusColor(systemStatus.status)}>
                          {getStatusText(systemStatus.status)}
                        </Tag>
                      </div>
                      <div>
                        <Text type="secondary">运行时间: </Text>
                        <Text strong>{systemStatus.uptime}</Text>
                      </div>
                      <div>
                        <Text type="secondary">环境: </Text>
                        <Tag color="blue">{systemStatus.environment}</Tag>
                      </div>
                    </Space>

                    <Space size="large" wrap>
                      <div>
                        <Text type="secondary">平台: </Text>
                        <Text>{systemStatus.platform}</Text>
                      </div>
                      <div>
                        <Text type="secondary">进程ID: </Text>
                        <Text code>{systemStatus.processId}</Text>
                      </div>
                      <div>
                        <Text type="secondary">主机名: </Text>
                        <Text>{systemStatus.machineName}</Text>
                      </div>
                      <div>
                        <Text type="secondary">.NET版本: </Text>
                        <Text>{systemStatus.dotnetVersion}</Text>
                      </div>
                    </Space>

                    <div style={{ marginTop: 16 }}>
                      <Space>
                        <Button
                          icon={<IconRefresh />}
                          onClick={loadSystemStatus}>
                          刷新状态
                        </Button>
                        <Button
                          type="primary"
                          status="danger"
                          icon={<IconPoweroff />}
                          onClick={handleGracefulShutdown}
                          disabled={systemStatus.status !== 'Running'}>
                          优雅关闭
                        </Button>
                      </Space>
                    </div>
                  </Space>
                )}
              </Card>

              {/* 待重启配置 */}
              <Card
                title="待重启配置"
                extra={
                  <Button
                    size="small"
                    icon={<IconRefresh />}
                    onClick={loadPendingRestart}>
                    刷新
                  </Button>
                }>
                {pendingRestart && pendingRestart.configs.length > 0 ? (
                  <Space direction="vertical" size="medium" style={{ width: '100%' }}>
                    <Alert
                      type="warning"
                      content={pendingRestart.instructions || '以下配置已修改,需要重启服务才能生效。'}
                    />
                    <Table
                      data={pendingRestart.configs}
                      pagination={false}
                      columns={[
                        {
                          title: '配置项',
                          dataIndex: 'configKey',
                          width: 200,
                        },
                        {
                          title: '旧值',
                          dataIndex: 'oldValue',
                          render: (val: string) => <Text code>{val || '(空)'}</Text>
                        },
                        {
                          title: '新值',
                          dataIndex: 'newValue',
                          render: (val: string) => <Text code type="success">{val || '(空)'}</Text>
                        },
                      ]}
                    />
                    <Alert
                      type="info"
                      content="请在合适的时间重启系统服务以应用这些配置更改。"
                    />
                  </Space>
                ) : (
                  <div style={{ textAlign: 'center', padding: '40px 0' }}>
                    <IconCheckCircle style={{ fontSize: 48, color: '#00b42a' }} />
                    <div style={{ marginTop: 16 }}>
                      <Text type="secondary">所有配置已生效,无需重启</Text>
                    </div>
                  </div>
                )}
              </Card>
            </Space>
          </TabPane>
        </Tabs>
      </Card>

      {/* 用户表单模态框 */}
      <Modal
        title={editingUser ? '编辑用户' : '创建用户'}
        visible={userModalVisible}
        onOk={handleSaveUser}
        onCancel={() => setUserModalVisible(false)}
        autoFocus={false}
        focusLock={true}>
        <Form form={userForm} layout="vertical">
          <FormItem
            label="用户名"
            field="username"
            rules={[{ required: true, message: '请输入用户名' }]}
            disabled={!!editingUser}>
            <Input placeholder="请输入用户名" disabled={!!editingUser} />
          </FormItem>

          {!editingUser && (
            <FormItem
              label="密码"
              field="password"
              rules={[{ required: true, message: '请输入密码' }]}>
              <Input.Password placeholder="请输入密码" />
            </FormItem>
          )}

          <FormItem
            label="邮箱"
            field="email"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' },
            ]}>
            <Input placeholder="请输入邮箱" />
          </FormItem>

          <FormItem
            label="显示名"
            field="displayName"
            rules={[{ required: true, message: '请输入显示名' }]}>
            <Input placeholder="请输入显示名" />
          </FormItem>
        </Form>
      </Modal>

      {/* 重置密码模态框 */}
      <Modal
        title="重置密码"
        visible={resetPasswordModalVisible}
        onOk={handleSaveResetPassword}
        onCancel={() => setResetPasswordModalVisible(false)}
        autoFocus={false}
        focusLock={true}>
        <Form form={resetPasswordForm} layout="vertical">
          <FormItem
            label="新密码"
            field="newPassword"
            rules={[{ required: true, message: '请输入新密码' }]}>
            <Input.Password placeholder="请输入新密码" />
          </FormItem>

          <FormItem
            label="确认密码"
            field="confirmPassword"
            rules={[
              { required: true, message: '请确认密码' },
              {
                validator: (value, callback) => {
                  if (
                    value !== resetPasswordForm.getFieldValue('newPassword')
                  ) {
                    callback('两次输入的密码不一致')
                  } else {
                    callback()
                  }
                },
              },
            ]}>
            <Input.Password placeholder="请再次输入新密码" />
          </FormItem>
        </Form>
      </Modal>

      {/* 用户角色管理模态框 */}
      <Modal
        title="管理用户角色"
        visible={roleModalVisible}
        onOk={handleSaveUserRoles}
        onCancel={() => setRoleModalVisible(false)}
        autoFocus={false}
        focusLock={true}>
        <Form layout="vertical">
          <FormItem label="选择角色">
            <Select
              mode="multiple"
              placeholder="请选择角色"
              value={selectedUserRoles}
              onChange={setSelectedUserRoles}
              style={{ width: '100%' }}>
              {allRoles.map((role) => (
                <Select.Option key={role.roleId} value={role.roleId}>
                  {role.roleName}
                </Select.Option>
              ))}
            </Select>
          </FormItem>
        </Form>
      </Modal>

      {/* 角色表单模态框 */}
      <Modal
        title={editingRole ? '编辑角色' : '创建角色'}
        visible={roleFormModalVisible}
        onOk={handleSaveRole}
        onCancel={() => setRoleFormModalVisible(false)}
        autoFocus={false}
        focusLock={true}>
        <Form form={roleForm} layout="vertical">
          <FormItem
            label="角色名称"
            field="roleName"
            rules={[{ required: true, message: '请输入角色名称' }]}
            disabled={!!editingRole}>
            <Input placeholder="请输入角色名称" disabled={!!editingRole} />
          </FormItem>

          <FormItem
            label="描述"
            field="description"
            rules={[{ required: true, message: '请输入描述' }]}>
            <Input.TextArea placeholder="请输入角色描述" rows={3} />
          </FormItem>

          <FormItem label="权限" field="permissionIds">
            <Select
              mode="multiple"
              placeholder="请选择权限"
              style={{ width: '100%' }}>
              {permissions.map((permission) => (
                <Select.Option
                  key={permission.permissionId}
                  value={permission.permissionId}>
                  {permission.permissionName} - {permission.description}
                </Select.Option>
              ))}
            </Select>
          </FormItem>
        </Form>
      </Modal>
    </div>
  )
}
